<template>
  <el-dialog class="formdrawer" :title="'预览备料单'" v-model="visible">
    <div style="display: flex; justify-content: flex-end; margin-bottom: 20px">
      <el-button type="primary" @click="viewBarcodeBtn">
        {{ $t("entirety.viewBarcode") }}
      </el-button>
    </div>

    <el-table
      :data="tableData"
      stripe
      height="69vh"
      border
      style="width: 90vw"
      :header-cell-style="{ background: '#fafafa', color: '#333' }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        prop="orderNo"
        :label="$t('tasksheet.orderNo')"
        width="180"
      />
      <!-- 动态判断 batch 字段是否为空 v-if="showBatchColumn"-->
      <el-table-column
        prop="batch"
        :label="$t('tasksheet.batch')"
        width="180"
      />
      <!-- <el-table-column
        prop="orderType"
        :label="$t('tasksheet.orderType')"
        width="180"
      /> -->
      <el-table-column
        prop="ingreNo"
        :label="$t('tasksheet.ingreNo')"
        width="180"
      />
      <el-table-column
        prop="ingreDesc"
        :label="$t('tasksheet.ingreDesc')"
        width="180"
      />
      <el-table-column prop="step" :label="$t('tasksheet.step')" width="180" />
      <el-table-column prop="qty" :label="$t('tasksheet.qty')" width="180" />
      <el-table-column prop="unit" :label="$t('tasksheet.unit')" width="180" />
      <el-table-column
        prop="protect"
        :label="$t('tasksheet.protect')"
        width="180"
      />
      <el-table-column
        prop="dosingType"
        :label="$t('tasksheet.dosingType')"
        width="180"
      />
      <el-table-column
        align="center"
        fixed="right"
        :label="$t('tasksheet.dosingType')"
        min-width="200px"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.dosingType == 1"
            plain
            type="primary"
            @click="dosingTypeBtn(scope.row)"
          >
            人工
          </el-button>
          <el-button
            v-if="scope.row.dosingType == 0"
            plain
            type="success"
            @click="dosingTypeBtn(scope.row)"
          >
            自动
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部的确认、取消按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancleBtn">{{ "关闭" }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { apigetsapDataByOrderNos } from "@/api/tasksheet";
import router from "@/router"; //路由跳转

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const tableData = ref([] as any);

// 切换 dosingType 的值
const dosingTypeBtn = (row: any) => {
  row.dosingType = row.dosingType === 0 ? 1 : 0;
};

// 动态行样式
const tableRowClassName = ({ row }: { row: any }) => {
  if (row.dosingType === 1) {
    return "warning-row";
  } else if (row.dosingType === 0) {
    return "success-row";
  }
  return "";
};

// 打开弹窗
const openDialog = (orderNoList: any) => {
  visible.value = true;
  if (orderNoList) {
    getElevatorInfoData(orderNoList); // 初始化表单数据的方法
  }
};
const pwsTable = ref([]);
const oneList = ref();
// 编辑：初始化表单数据
// const getElevatorInfoData = async (orderNoList: string) => {
//   tableData.value = [];
//   loading.value = true;

//   try {
//     const res = await apigetsapDataByOrderNos(orderNoList); // 编辑回显接口

//     // 使用 reduce 进行数据合并
//     const mergedData = res.data.reduce((acc, item) => {
//       const existing = acc.find((entry) => entry.orderNo === item.orderNo);
//       if (existing) {
//         // 如果已有相同 orderNo，则合并 sapDataRgblVoList
//         existing.sapDataRgblVoList = [
//           ...(existing.sapDataRgblVoList || []),
//           ...(item.sapDataRgblVoList || []),
//         ];
//       } else {
//         // 否则直接添加
//         acc.push({ ...item });
//       }
//       return acc;
//     }, [] as typeof res.data);

//     // 处理 sapDataRgblVoList，展开并过滤 batch 为空的项
//     tableData.value = mergedData.flatMap((item) =>
//       (item.sapDataRgblVoList || []).filter((row) => row.batch)
//     );

//     console.log(7777, tableData.value);

//     // 继续处理其他数据
//     pwsTable.value = mergedData[0]?.pwsTable || [];
//   } catch (error) {
//     console.error("Error fetching data:", error);
//   } finally {
//     loading.value = false;
//   }
// };

const getElevatorInfoData = async (orderNoList: string) => {
  tableData.value = [];
  loading.value = true;

  try {
    const res = await apigetsapDataByOrderNos(orderNoList); // 编辑回显接口

    // 先执行 flatMap 和 filter 操作
    tableData.value = res.data
      .flatMap((item) => item.sapDataRgblVoList || []) // 展平列表
      .filter((row) => row.ingreNo); // 过滤掉 ingreNo 为空的行

    // 确保 tableData.value 已经赋值后再打印

    // 继续处理其他数据
    pwsTable.value = res.data[0]?.pwsTable || [];
  } catch (error) {
    console.error("Error fetching data:", error);
  } finally {
    loading.value = false;
  }
};
// const getElevatorInfoData = (orderNoList: string) => {
//   tableData.value = [];
//   loading.value = true;
//   apigetsapDataByOrderNos(orderNoList) // 编辑回显接口
//     .then((res: any) => {
//       tableData.value = res.data
//         .flatMap((item) => item.sapDataRgblVoList || []) // 展平列表
//         .filter((row) => row.batch); // 过滤掉 batch 为空的行
// console.log(7777, tableData.value );

//       pwsTable.value = res.data[0]?.pwsTable || [];
//       // }

//       // 【过滤掉接口中 batch 字段为空的数据】
//       // tableData.value = res.data.filter((row: any) => row.batch !== "");
//       // tableData.value = res.data[0].sapDataRgblVoList.filter(
//       //   (row: any) => row.batch !== ""
//       // );

//       // tableData.value = res.data
//       //   .flatMap((item: any) => {
//       //     oneList.value = item.sapDataRgblVoList;
//       //   })
//       //   .filter((row: any) => {
//       //     row.batch !== "";
//       //   }); // 筛选 batch !== ""

//       // tableData.value = res.data
//       //   .flatMap((item: any) => item.sapDataRgblVoList) // 合并所有 sapDataRgblVoList
//       //   .filter((row: any) => row.batch !== ""); // 筛选 batch !== ""

//       // pwsTable.value = res.data[0].pwsTable;
//     })
//     .finally(() => {
//       loading.value = false;
//     });
// };

// 取消按钮
const cancleBtn = () => {
  visible.value = false;
};
// 1.引入bus
// import emitter from "@/utils/eventbus";

// const barcodeList=ref([])
const viewBarcodeBtn = () => {
  // 【获取 dosingType 值为 1 ，所在行的 id ，存成数组】
  const idList = tableData.value
    .filter((row: any) => row.dosingType === 1)
    .map((row: any) => row.id);

  const dosingTypeRows = ref([]);
  tableData.value.forEach((item: any) => {
    if (item.dosingType == 1) {
      dosingTypeRows.value.push(item);
    }
  });
  // emitter.emit("event", idList);
  router.push({
    path: "/tasksheet/getProductionOrder/barCode",
    query: { idList }, //【query 只能接受字符串类型的数据，而 rows 是一个对象数组】
  });
  // console.log(777,idList);
  
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.blue-background {
  background-color: #007bff !important; /* 蓝色背景 */
  color: white !important; /* 白色文字 */
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
